package com.gzgs.controller;

import com.gzgs.domain.Role;
import com.gzgs.domain.UserInfo;
import com.gzgs.service.UserService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有的用户
     */
    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<UserInfo> userInfolist = userService.findAll();
        mv.addObject("userList", userInfolist);
        mv.setViewName("user-list");
        return mv;
    }

    /**
     * 新建用户
     */
    @RequestMapping("/save.do")
    public String saveUser(UserInfo user) throws Exception {
        userService.saveUser(user);
        return "redirect:findAll.do";
    }


    /**
     * 查询用户详情
     */
    @RequestMapping("findById.do")
    public ModelAndView findById(String id)throws Exception{
        ModelAndView mv=new ModelAndView();
        UserInfo user=userService.findById(id);
        mv.addObject("user",user);
        mv.setViewName("user-show");
        return  mv;
    }

    /**
     * 查询用户可添加的角色
     */
    @RequestMapping("findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) throws Exception {
        ModelAndView mv= new ModelAndView();
        UserInfo user=userService.findById(userid);
        List<Role> roleList=userService.findOtherRole(userid);
        mv.addObject("user",user);
        mv.addObject("roleList",roleList);
        mv.setViewName("user-role-add");
        return  mv;
    }

    /**
     * 给用户添加角色
     */
    @RequestMapping("addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId", required = true) String userId, @RequestParam(name = "ids", required = true) String[] roleIds) throws Exception {
        userService.addRoleToUser(userId,roleIds);
        return "redirect:findAll.do";
    }

}
